var express = require("express");
var router = express.Router();
var db = require("../sql.js");
var multiparty = require("multiparty");

/* GET users listing. */
router.post("/", function (req, res, next) {
  var from = new multiparty.Form();
  //   上传的文件保存的路径，必须存在
  from.uploadDir = "./public/upload";

  from.parse(req, function (err, fields, files) {
    console.log(files, fields);

    var bannerName = fields.imgName[0];
    // var bannerUrl = fields.bannerUrl[0];
    var bannerImg = files.pic[0].path;
    db.query(
      "insert into banner value (?,?,?)",
      [0, bannerName, bannerImg],
      function (err, result) {
        if (err) {
          console.log(err);
          return;
        }
        db.query("select * from banner", function (err, result) {
          var pager = {};
          // 当前页码
          pager.pageCurrent = 1;
          // 总条数
          pager.maxNum = result.length;
          // 每页条数
          pager.pageSize = 5;
          // 总页数
          pager.pageCount = parseInt(Math.ceil(pager.maxNum / pager.pageSize));
          // 页码列表
          var dataList = result.slice(
            (pager.pageCurrent - 1) * pager.pageSize,
            (pager.pageCurrent - 1) * pager.pageSize + pager.pageSize
          );

          if (err) {
            console.log(err);
            return;
          }
          // console.log(result);
          res.render("bannerList", {
            bannerList: dataList,
            pager: pager,
          });
        });
        
      }
    );
  });
});
module.exports = router;
